package com.idbk.chargestation.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.idbk.chargestation.AppContext;
import com.idbk.chargestation.R;
import com.idbk.chargestation.activity.charge.ActivityComment;
import com.idbk.chargestation.activity.user.ActivityLogin;
import com.idbk.chargestation.activity.pile.ActivityPointDetail;
import com.idbk.chargestation.adapter.PointCommentAdapter;
import com.idbk.chargestation.api.APIForPoint;
import com.idbk.chargestation.bean.JsonComment;
import com.idbk.chargestation.bean.JsonCommentList;
import com.idbk.chargestation.bean.JsonCommentResult;
import com.idbk.chargestation.net.EHttpResponse;
import com.idbk.chargestation.util.Const;
import com.idbk.chargestation.util.FlagRequest;
import com.idbk.chargestation.util.GsonUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 评论Fragment
 *
 * @author liangzw, lupc
 */
public class FragmentComments extends Fragment implements OnClickListener {

    private final static String TAG = "FragmentComments";

    private View mView;
    private Context mContext;
    private List<JsonComment> mData;

    private PullToRefreshListView mListView;
    private PointCommentAdapter mAdapter;//定义一个适配器

    public final static int PAGE_SIZE = 10;
    private int pageIndex = 1;

    private int mPointId;
    private LinearLayout mLayoutEmpty, mLayoutError;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        mView = inflater.inflate(R.layout.fragment_comments, container, false);

        mContext = getActivity();

        setupView();

        setupData();

        return mView;
    }

    private void setupView() {
        mView.findViewById(R.id.textview_comment).setOnClickListener(this);
        mLayoutEmpty = (LinearLayout) mView.findViewById(R.id.tj_empty_view);
        mLayoutError = (LinearLayout) mView.findViewById(R.id.tj_error_view);
        mLayoutError.setOnClickListener(this);
        mListView = (PullToRefreshListView) mView.findViewById(R.id.fragment_comments_list);
        mListView.setMode(Mode.BOTH);
        mListView.setOnRefreshListener(new OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                //下拉的时候数据重置
                APIForPoint.getPointComments(mPointId, 1, PAGE_SIZE, mResponseReload);
            }

            @Override
            public void onPullUpToRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                //上拉的时候添加选项
                APIForPoint.getPointComments(mPointId, ++pageIndex, PAGE_SIZE, mResponseMore);
            }
        });
        //定义适配器
        mData = new ArrayList<JsonComment>();
        mAdapter = new PointCommentAdapter(mContext, mData);
        mListView.setAdapter(mAdapter);
    }

    private void setupData() {
        mPointId = getArguments().getInt(Const.KEY_ID);
        APIForPoint.getPointComments(mPointId, 1, PAGE_SIZE, mResponse);
    }

    //刷新评论列表（第一次加载、下拉刷新）
    private final EHttpResponse mResponse = new EHttpResponse() {

        @Override
        public void onEResponse(String response) {
            JsonCommentList result = GsonUtils.toBean(JsonCommentList.class, response);
            if (result.status == 0) {
                mLayoutError.setVisibility(View.GONE);
                mLayoutEmpty.setVisibility(View.GONE);
                mListView.setVisibility(View.VISIBLE);
                pageIndex = 1;
                mData.clear();
                bindRefreshData(result);
            } else {
                //异常返回
                Toast.makeText(mContext, result.message, Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onEErrorResponse(VolleyError error) {
            //打印调试信息
            Log.e(TAG, error.getMessage(), error.getCause());
            mLayoutError.setVisibility(View.VISIBLE);
            mLayoutEmpty.setVisibility(View.GONE);
            mListView.setVisibility(View.GONE);
            Toast.makeText(mContext, R.string.common_tip_resultfail, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onEFinish() {
            super.onEFinish();
        }

    };

    //下拉重置
    private final EHttpResponse mResponseReload = new EHttpResponse() {

        @Override
        public void onEResponse(String response) {
            JsonCommentList result = GsonUtils.toBean(JsonCommentList.class, response);
            if (result.status == 0) {
                pageIndex = 1;
                mData.clear();
                bindRefreshData(result);
            } else {
                //异常返回
                Toast.makeText(mContext, result.message, Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onEErrorResponse(VolleyError error) {
            //打印调试信息
            Log.e(TAG, error.getMessage(), error.getCause());
            mLayoutError.setVisibility(View.VISIBLE);
            mLayoutEmpty.setVisibility(View.GONE);
            mListView.setVisibility(View.GONE);
        }

        @Override
        public void onEFinish() {
            super.onEFinish();
            mListView.onRefreshComplete();
        }
    };

    //上拉加载
    private final EHttpResponse mResponseMore = new EHttpResponse() {

        @Override
        public void onEResponse(String response) {
            JsonCommentList result = GsonUtils.toBean(JsonCommentList.class, response);
            if (result.status == 0) {
                if (result.total < 1 || result.commentItems == null) {
                    Toast.makeText(mContext, "没有更多数据了", Toast.LENGTH_SHORT).show();
                } else {
                    pageIndex += 1;
                    bindRefreshData(result);
                }
            } else {
                //异常返回
                Log.e(TAG, "onEResponse: mResponseMore error statue:" + result.status + " msg :" + result.message);
            }
        }

        @Override
        public void onEErrorResponse(VolleyError error) {
            //打印调试信息
            Log.e(TAG, error.getMessage(), error.getCause());
            mLayoutError.setVisibility(View.VISIBLE);
            mLayoutEmpty.setVisibility(View.GONE);
            mListView.setVisibility(View.GONE);
        }

        @Override
        public void onEFinish() {
            super.onEFinish();
            mListView.onRefreshComplete();
        }

    };

    private void bindRefreshData(JsonCommentList result) {
        mListView.setVisibility(View.VISIBLE);
        if (result != null) {
            if (result.commentItems != null) {
                mData.addAll(result.commentItems);
            } else {
                mLayoutError.setVisibility(View.GONE);
                mLayoutEmpty.setVisibility(View.VISIBLE);
                mListView.setVisibility(View.GONE);
            }
            mAdapter.notifyDataSetChanged();
            //评论总数使用实际读回来的值
            if (getActivity() != null) {
                ((ActivityPointDetail) getActivity()).setCommentCount(result.total);
            }
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, requestCode, intent);
        if (requestCode == FlagRequest.REQUEST_COMMENT &&
                resultCode == Activity.RESULT_OK) {
            //将新数据加载到列表
            JsonCommentResult.JsonCommentResultInfo data = intent.getParcelableExtra(JsonCommentResult.JsonCommentResultInfo.KEY);
            if (data != null) {
                mLayoutError.setVisibility(View.GONE);
                mLayoutEmpty.setVisibility(View.GONE);
                mListView.setVisibility(View.VISIBLE);
                JsonComment item = data.toJsonComment();
                mData.add(0, item);
                mAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tj_error_view:
                setupData();
                break;
            case R.id.textview_comment:
                if (AppContext.getInstance().isLogin()) {
                    Intent intent = new Intent(mContext, ActivityComment.class);
                    intent.putExtra(Const.KEY_ID, mPointId);
                    startActivityForResult(intent, FlagRequest.REQUEST_COMMENT);
                } else {
                    Intent intent = new Intent(mContext, ActivityLogin.class);
                    startActivity(intent);
                }
                break;
            default:
                break;
        }
    }

}
